package com.atguigu.gulimall.gulimallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.gulimallmember.dao.MemberLevelDao;
import com.atguigu.gulimall.gulimallmember.entity.MemberLevelEntity;
import com.atguigu.gulimall.gulimallmember.exception.PhoneExistExcrption;
import com.atguigu.gulimall.gulimallmember.exception.UsernameExistException;
import com.atguigu.gulimall.gulimallmember.service.MemberLevelService;
import com.atguigu.gulimall.gulimallmember.vo.MemberLoginVo;
import com.atguigu.gulimall.gulimallmember.vo.MemberRegistVo;
import com.atguigu.gulimall.gulimallmember.vo.SocialUser;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.gulimallmember.dao.MemberDao;
import com.atguigu.gulimall.gulimallmember.entity.MemberEntity;
import com.atguigu.gulimall.gulimallmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    //注册功能
    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        MemberDao baseMapper = this.baseMapper;

        //设置默认会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

        entity.setNickname(vo.getUserName());

        //密码加密存储
        //MD5不能直接进行密码的加密存储(彩虹表，通过大量枚举md5的结果在逆转的时候查询该表以返回结果)

        //盐值加密 采用spring家的BCryptPasswordEncoder,可以通过加密结果自己解析密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他的默认信息

        //保存
        baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistExcrption {
        MemberDao baseMapper = this.baseMapper;
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExistExcrption();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("username", username));
        if(count>0){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword(); //123456

        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or()
                .eq("mobile", loginacct));
        if(entity == null){
            //登录失败
            return null;
        }else{
            //1.获取到数据库存储的密码$2a$10$lNGFxdwNXFQwxjiFEfGJv.xcZ1e76d3CF3XTMW49YZJVSUmY3pt6y
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            //2.密码匹配
            boolean matches = encoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        //登录和注册合并逻辑
//        String uid = vo.getUid();


        MemberEntity memberEntity = new MemberEntity();
        JSONObject jsonObject = null;

        HashMap<String, String> query = new HashMap<>();
        query.put("access_token",vo.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user",
                "get", new HashMap<String, String>(),
                query);
        String id = null;   //用户唯一ID
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            jsonObject = JSON.parseObject(json);
            id = jsonObject.getString("id");

            MemberDao baseMapper = this.baseMapper;
            memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                    .eq("social_id", id));
        }
        //1.判断当前社交用户是否已经登陆过系统（即判断该社交方式登录的用户
        // 之前是否已经以该方式登录过，登录过则更新其令牌有效时间即访问令牌）

        if (memberEntity != null) {
            //这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in());

            baseMapper.updateById(update);

            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());

            return memberEntity;
        }else{
            //2.没有查到当前社交用户(使用该社交方式)登录过该系统),为其注册

            //3.查询当前社交用户的社交账号信息
            //查询成功
            //regist 包含注册信息
            MemberEntity regist = new MemberEntity();
            String name = jsonObject.getString("name");
            regist.setNickname(name);
            //拿到查询社交用户个人信息中的唯一ID
            regist.setSocialId(id);

            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiresIn(vo.getExpires_in());

            baseMapper.insert(regist);
            return regist;
        }
    }

}